import config from "../../config/index.js";
import store from "../../store/index.js";

const tool = {

    /**
     * 随机去到一个网站
     */
    toTraveling: () => {
        tool.snackbarShow('暂未实现');
    },

    /**
     * 随机去到一篇文章
     */
    toRandomPost: () => {
        tool.snackbarShow('暂未实现');
    },

    /**
     * 是否在文章页面
     * @returns {boolean} 是否
     */
    isArticlePageByHash: function (hash) {
        return hash.indexOf("#article") >= 0 || hash.indexOf("#/article") === 0 || hash.indexOf("/article") === 0 ||
            hash.indexOf("#Article") >= 0 || hash.indexOf("#/Article") === 0 || hash.indexOf("/Article") === 0;
    },

    switchArticlePage: function (hash) {
        store.commit("SET_IS_ARTICLE_PAGE", tool.isArticlePageByHash(hash));
    },

    /**
     * 是否在首页
     * @returns {boolean} 是否
     */
    isIndexPageByHash: function (hash) {
        return hash.indexOf("#index") >= 0 || hash.indexOf("#/index") === 0 || hash.indexOf("/index") === 0 ||
            hash.indexOf("#Index") >= 0 || hash.indexOf("#/Index") === 0 || hash.indexOf("/Index") === 0;
    },

    /**
     * 是否在首页
     * @returns {boolean} 是否
     */
    switchIndexPage: function (hash) {
        store.commit("SET_IS_INDEX_PAGE", tool.isIndexPageByHash(hash));
    },

    /**
     * 当前选中内容
     * @returns {string} 当前选中内容
     */
    selectText: function () {
        let text;
        if (document.selection) {
            text = document.selection.createRange().text;
        } else {
            text = window.getSelection() + '';
        }
        return text;
    },

    imageToBlob: function (imageURL) {
        return new Promise(function (resolve) {
            const img = new Image();
            const c = document.createElement("canvas");
            const ctx = c.getContext("2d");
            img.crossOrigin = "";
            img.onload = function () {
                c.width = this.naturalWidth;
                c.height = this.naturalHeight;
                ctx.drawImage(this, 0, 0);
                c.toBlob(function (blob) {
                    resolve(blob);
                }, "image/png", 0.75);
            };
            img.src = imageURL;
        });
    },

    copyImage: async function (imageURL) {
        const blob = await tool.imageToBlob(imageURL);
        const item = new ClipboardItem({"image/png": blob});
        navigator.clipboard.write([item]);
    },

    /**
     * 下载图片状态
     */
    imgDownloading: false,

    /**
     * 复制图片到剪贴板
     * @param imgSrc 图片地址
     */
    writeClipImg: function (imgSrc) {
        tool.snackbarShow('正在下载中，请稍后', false, 10000);
        if (tool.imgDownloading === false) {
            tool.imgDownloading = true;
            setTimeout(function () {
                tool.copyImage(imgSrc).then(() => {
                    tool.snackbarShow('复制成功！图片已添加盲水印，请遵守版权协议');
                    tool.imgDownloading = false;
                })
            }, 10000);
        }
    },

    downloadImage: function (imgSrc, name) {
        if (tool.downloadimging === false) {
            tool.downloadimging = true;
            tool.snackbarShow('正在下载中，请稍后', false, 10000)
            setTimeout(function () {
                let image = new Image();
                // 解决跨域 Canvas 污染问题
                image.setAttribute("crossOrigin", "anonymous");
                image.onload = function () {
                    let canvas = document.createElement("canvas");
                    canvas.width = image.width;
                    canvas.height = image.height;
                    let context = canvas.getContext("2d");
                    context.drawImage(image, 0, 0, image.width, image.height);
                    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
                    let a = document.createElement("a"); // 生成一个a元素
                    let event = new MouseEvent("click"); // 创建一个单击事件
                    a.download = name || "photo"; // 设置图片名称
                    a.href = url; // 将生成的URL设置为a.href属性
                    a.dispatchEvent(event); // 触发a的单击事件
                };
                image.src = imgSrc;
                tool.snackbarShow('图片已添加盲水印，请遵守版权协议');
                tool.downloadimging = false;
            }, "10000");
        } else {
            tool.snackbarShow('有正在进行中的下载，请稍后再试');
        }
    },

    copyUrl: function (id) {
        document.body.insertAdjacentHTML('afterend', "<input id='copyVal'></input>");
        const text = id;
        const input = document.getElementById("copyVal");
        input.value = text;
        input.select();
        input.setSelectionRange(0, input.value.length);
        document.execCommand("copy");
        document.getElementById("copyVal").remove();
    },

    rightMenuCopyText: function (text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text);
        }
    },

    copyPageUrl: function () {
        const url = window.location.href;
        tool.copyUrl(url);
        tool.snackbarShow('复制本页链接地址成功', false, 2000);
    },

    sharePage: function () {
        const url = window.location.href;
        tool.copyUrl(url);
        tool.snackbarShow('复制本页链接地址成功', false, 2000);
    },

    insertAtCaret: function (element, value) {
        const startPos = element.selectionStart;
        const endPos = element.selectionEnd;
        if (document.selection) {
            element.focus();
            const sel = document.selection.createRange();
            sel.text = value;
            element.focus();
        } else {
            if (startPos || startPos === '0') {
                const scrollTop = element.scrollTop;
                element.value = element.value.substring(0, startPos) + value + element.value.substring(endPos, element.value.length);
                element.focus();
                element.selectionStart = startPos + value.length;
                element.selectionEnd = startPos + value.length;
                element.scrollTop = scrollTop;
            } else {
                element.value += value;
                element.focus();
            }
        }
    },

    readClipboard: function (globalEvent) {
        if (navigator.clipboard) {
            navigator.clipboard.readText().then(function (clipText) {
                tool.insertAtCaret(globalEvent.target, clipText);
            });
        }
    },

    pasteText: function () {
        const result = tool.readClipboard() || '';
    },

    searchBaidu: function (selectTextNow) {
        tool.snackbarShow('即将跳转到百度搜索', false, 2000);
        setTimeout(function () {
            window.open('https://www.baidu.com/s?wd=' + selectTextNow);
        }, 2000);
    },

    copyLink: function (href) {
        tool.rightMenuCopyText(href);
        tool.snackbarShow('已复制链接地址');
    },

    // 引用到评论
    rightMenuCommentText: function (text) {
        const input = document.getElementsByClassName(config.source.comments.textarea)[0];
        let evt = document.createEvent('HTMLEvents');
        evt.initEvent('input', true, true);
        let inputValue = tool.replaceAll(text, '\n', '\n> ')
        input.value = '> ' + inputValue + '\n\n';
        input.dispatchEvent(evt);
        const domTop = document.querySelector("#post-comment").offsetTop;
        window.scrollTo(0, domTop - 80);
        input.focus();
        input.setSelectionRange(-1, -1);
        if (document.getElementById("comment-tips")) {
            document.getElementById("comment-tips").classList.add("show");
        }
    },

    snackbarShow: (text, showActionFunction = false, duration = 2000, actionText = false) => {
        const {position, bgLight, bgDark} = config.snackbar;
        const bg = document.documentElement.getAttribute("theme_mode") === "light" ? bgLight : bgDark;
        const root = document.querySelector(":root");
        root.style.setProperty("--heo-snackbar-time", duration + "ms");
        Snackbar.show({
            text: text,
            backgroundColor: bg,
            onActionClick: showActionFunction,
            actionText: actionText,
            showAction: actionText,
            duration: duration,
            pos: position,
            customClass: "snackbar-css",
        });
    },

    sidebarPaddingR: () => {
        const innerWidth = window.innerWidth
        const clientWidth = document.body.clientWidth
        const paddingRight = innerWidth - clientWidth
        if (innerWidth !== clientWidth) {
            document.body.style.paddingRight = paddingRight + 'px'
        }
    },

    fadeIn: (ele, time) => {
        ele.style.cssText = `display:block;animation: to_show ${time}s`
    },

    fadeOut: (ele, time) => {
        ele.addEventListener('animationend', function f() {
            ele.style.cssText = "display: none; animation: '' "
            ele.removeEventListener('animationend', f)
        })
        ele.style.animation = `to_hide ${time}s`
    },

    isHidden: (ele) => ele.offsetHeight === 0 && ele.offsetWidth === 0,

    replaceAll: (string, search, replace) => string.split(search).join(replace),

    openLink: (url, target = "_blank") => {
        let linkElement = document.createElement("a");
        linkElement.setAttribute("href", url);
        linkElement.setAttribute("target", target);
        linkElement.setAttribute("rel", "noreferrer noopener");
        linkElement.setAttribute("id", "external");
        let existingLink = document.getElementById("external");
        if (existingLink) {
            document.body.removeChild(existingLink);
        }
        document.body.appendChild(linkElement);
        linkElement.click();
        linkElement.remove();
    },

    changeContent: (content, length = null) => {
        if (content === '') return content
        content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
        content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
        content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
        content = content.replace(/<[^>]+>/g, "") // remove html tag
        if (length !== null) {
            if (content.length > length) {
                content = content.substring(0, length) + '...'
            }
        }
        return content;
    }

}

export default tool;